<template>
  <view class='loadContainer'>
    <view class="loadTip" v-if="loadStatus !== -1">
			<text v-if="loadStatus === 1">{{ loadTxt }}</text>
      <text @click="reQuest" v-else-if="loadStatus !== 2">{{ loadTxt }}</text>
      <slot v-else>
        {{ loadTxt }}
      </slot>
    </view>
  </view>
</template>
<script>
/**
 * 描述：后台分页请求的封装
 *  loadStatus（对应的列表底部的加载文案）： -1 无提示 0 加载完毕 1 加载中 2 没有更多数据 3 加载失败点击重试，
 * 
 */
export default {
  props: {
    update: {
      type: Boolean,
      default: true
    }, // 是否有更新进行请求
    refresh: {
      type: Boolean,
      default: false
    }, // 是否有更新进行请求
    list: {
      type: Array,
      default: () => []
    }, // 当前列表
    params: {
      type: Object,
      default: () => {
        pageSize: 10
      }
    }, // 必须包含每页数量pageSize，还有其它的请求条件
    url: {
      type: String,
      default: ''
    }, // 后台服务name在API中对应
    deep: {
      type: String,
      default: ''
    }
  },
  data() {
    this.hasNext = true;
    this.pageIndex = 1;
    return {
      loadStatus: 1
    }
  },
  computed: {
    loadTxt () {
      var _loadTxt = ''
      switch (this.loadStatus) {
        case -1:
          _loadTxt = ''
          break;
        case 0:
          _loadTxt = '上拉加载更多'
          break;
        case 1:
          _loadTxt = '正在加载中'
          break;
        case 2:
          _loadTxt = '没有更多数据了'
          break;
        case 3:
          _loadTxt = '网络连接异常,点击重试'
          break;
        default: console.log('加载状态码异常！！')
      }
      return _loadTxt
    }
  },
  watch: {
    update(newValue, oldValue) {
      if (newValue !== oldValue) {
        if (this.hasNext) {
          this.requestList()
        } else {
          this.loadStatus = 2
        }
      }
    },
    refresh(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.loadStatus  = 1
        this.refreshHandler()
      }
    }
  },
  methods: {
    reQuest () { // 请求失败，重试
      if (this.loadStatus === 3) {
        this.requestList()
      }
    },
    refreshHandler () {
      Object.assign(this.$data, this.$options.data()) // 页面再次加载后数据重置一下 注意：data应该使用函数返回值方式
      this.requestList()
    },
    mockData(pageSize, total, pageIndex) { // pageSize 每页数量量 total 符合条件的数据总量 pageIndex 当前页码
      let datas = [];
      for (let i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize && i < total; i++) {
        datas.push({name: '姜中希' + i, mobilePhone: '13718612674', id: i})
      }
      let hasNext = false;
      if (pageSize * pageIndex < total) {
        hasNext = true;
      }
			
      let res = {
        result: 'success',
        data: {
          hasNext: hasNext,
          totalCount: total,
          datas: datas
        },
      }
      return res
    },
    filterData (data, total, size) { // 列表数据、总数据、当前页数据
      let datas = data.filter((item, index) => {
        if (index < size) {
          return true
        } else {
          return false
        }
      })
      let res = {
        result: 'success',
        data: {
          hasNext: false,
          totalCount: total,
          datas: datas
        },
      }
      return res
    },
    requestList () {
      if (this.loadStatus === 2 || this.loadStatus === -1) {
        return
      }
			
      this.loadStatus  = 1
      this.http.GET({
        name: this.url,
        params: Object.assign({pageIndex: this.pageIndex}, this.params),
        rejectLoadingTip: true
      }).then(res => {
				// let res = this.mockData(18, 36, 1)
        uni.stopPullDownRefresh() // 下拉刷新操作在成功获取数据后停止动画
        if (res.result === 'success') { // 返回成功状态
          let otherData = {categoryList: [], brandList: []};
          if (this.deep) {
            if(JSON.stringify(res.data) === '{}') {
              this.$emit('bind_list', [], otherData)
              this.loadStatus = -1
              return;
            }
            Object.assign(otherData, res.data)
            res.data = res.data[this.deep]
            if(!res.data.categoryList) {
              otherData.categoryList
            }
          }
          let list = this.list.slice(0)
          this.hasNext = res.data.hasNext
          if (res.data.hasNext) { // 如果有下一页的话
            this.loadStatus = 0
            if (this.pageIndex === 1) { // 如果是第一次请求那么列表是替换（防止首次请求列表数据缓存导致重复数据）
              list = res.data.datas           
            } 
            else {
              list = list.concat(res.data.datas) // 叠加数组
            }
            this.pageIndex++
          } else { // 最后一页状态
            if (res.data.totalCount <= this.params.pageSize) { // 当前列表只有一页数据
              list = res.data.datas
              this.loadStatus = -1
            } else { // 当前列表有多页数据，当前页是最后一页
              this.loadStatus = 2
              list = list.concat(res.data.datas) // 叠加数组
            }
          }
          this.$emit('bind_list', list, otherData)
        } else {
          if (res.msg === '请登录账号' || res.msg === '会员不存在') {
            this.$emit('bind_list', [], {categoryList: [], brandList: []})
          } else {
            this.loadStatus = 3
          }
        }
        return res
      }).catch(() => {
        this.loadStatus = 3
      })
    }
  }
}
</script>
<style scoped>
  .loadContainer {
    width: 100%;
    background: transparent;
  }
 .loadTip {
    width: 100%;
    background: transparent;
    text-align: center;
    font-size: 25rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999999;
    padding: 20upx;
  }
  .loadTip text {
    color: #999999;
    padding: 10upx;
  }
  .loadTip image{
    width: 30rpx;
    height: 30rpx;
    margin-right: 20rpx;
    animation: rotating 1.2s linear infinite;
  }
  @keyframes rotating{
    from{transform:rotate(0)}
    to{transform:rotate(360deg)}
  }
  .pagination {
    width: 100%;
  }
</style>
